package com.campus.client.controller;

import com.campus.client.net.ClientConnector;
import com.campus.client.view.TeacherRegisterFrame;
import com.campus.common.message.TeacherRegisterResponse;
import com.campus.common.vo.Teacher;

import javax.swing.*;
        import java.awt.*;
        import java.io.IOException;

public class TeacherController extends Component {
    private TeacherRegisterFrame teacherRegisterFrame;
    private ClientConnector connector;

    public TeacherController(TeacherRegisterFrame teacherRegisterFrame, ClientConnector connector) {
        this.teacherRegisterFrame = teacherRegisterFrame;
        this.connector = connector;
        setupEventHandlers();
    }

    private void setupEventHandlers() {
        // 设置登录按钮事件
        teacherRegisterFrame.setRegisterButtonAction(event -> {
            try {
                registerControl();
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        teacherRegisterFrame.setBackButtonAction(event -> {

            try {
                teacherRegisterFrame.showLoginFrame();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        });

    }

    private String registerControl() throws ClassNotFoundException, IOException {

        if (teacherRegisterFrame.getTeacherId().isEmpty()||teacherRegisterFrame.getPassword().isEmpty()||
        teacherRegisterFrame.getName().isEmpty()||teacherRegisterFrame.getDepartment().isEmpty()||
                teacherRegisterFrame.getContact().isEmpty()) {
            JOptionPane.showMessageDialog(this,
                    "个人信息不能为空！",
                    "输入错误",
                    JOptionPane.ERROR_MESSAGE);
            return "None";
        }

        Teacher teacher = new Teacher(teacherRegisterFrame.getTeacherId(),teacherRegisterFrame.getName(),teacherRegisterFrame.getGender()
        ,Integer.valueOf(teacherRegisterFrame.getAge()),teacherRegisterFrame.getDepartment(),teacherRegisterFrame.getContact());





        TeacherRegisterResponse resp = connector.register(teacherRegisterFrame.getTeacherId(),teacherRegisterFrame.getPassword(),teacher);

        if(resp.isSuccess()){
            teacherRegisterFrame.showLoginFrame();

            JOptionPane.showMessageDialog(this,
                    "注册成功！\n欢迎您的到来，" + teacher.getTeacherId() + "！",
                    "注册成功",
                    JOptionPane.INFORMATION_MESSAGE);
        }
        else{
            JOptionPane.showMessageDialog(this,
                    "该用户名已注册！",
                    "输入错误",
                    JOptionPane.ERROR_MESSAGE);
        }

        return resp.getMessage();


    }

}
